using System;
using System.IO;
using System.Diagnostics;
using System.Collections;
using System.Configuration;
using System.Security.Cryptography.X509Certificates;
using CAPICOM;
using Microsoft.VisualBasic;

namespace CertificateConvert
{
	class CertificateConvert
	{
		static private String[] stores = {"Root","CA"};        
        static private String keyStorePassword = "changeit";
		static StoreClass oStore;
		static Certificates oCerts;
		static String filter = "";

		[STAThread]
		static void Main(string[] args)
		{
            string keytoolPath = ConfigurationSettings.AppSettings.Get("keyToolPath");
            string basePath = ConfigurationSettings.AppSettings.Get("basePath");
            string keyStorePath = basePath + "\\cacerts-win32.jks";
            string keyStorePassword = ConfigurationSettings.AppSettings.Get("keyStorePassword");

            // Record the base path
            DirectoryInfo dir = new DirectoryInfo(basePath);
            try
            {
                if (dir.Exists == false)
                    dir.Create();

                dir.CreateSubdirectory("certificates");
            }
            catch (IOException e) 
            {
                Console.WriteLine("Unable to create necessary directories" + e.Message);
                Environment.Exit(0);
            }

            foreach (String storeName in stores)
            {
                // Make sure all the directories are configured                
                try
                {                    
                    dir.CreateSubdirectory("certificates\\" + storeName);                    
                }
                catch (IOException e)
                {
                    Console.WriteLine("Unable to create necessary directories" + e.Message);
                    Environment.Exit(0);
                }
                
                oStore = new StoreClass();
                oStore.Open(
                  CAPICOM_STORE_LOCATION.CAPICOM_CURRENT_USER_STORE,
                  storeName, CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_EXISTING_ONLY |
                  CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_READ_ONLY
                );
                oCerts = (Certificates)oStore.Certificates;
                oCerts = (Certificates)oCerts.Find(CAPICOM_CERTIFICATE_FIND_TYPE.CAPICOM_CERTIFICATE_FIND_SUBJECT_NAME, filter, false);

                Console.WriteLine("\n{0} certificates in the " + storeName + "Store\n", oCerts.Count, filter + " ");

                IEnumerator certenum = oCerts.GetEnumerator();
                int counter = 1;
                int certCount = oCerts.Count;

                while (certenum.MoveNext())
                {
                    Certificate ocert = (Certificate)certenum.Current;
                    Console.Write(counter + ":" + certCount + " " + ocert.SubjectName + ". ");

                    // Export the individual certificates
                    String filename = basePath + "\\certificates\\" + storeName + "\\" + ocert.Thumbprint + ".cer";
                    ocert.Save(filename, "password", CAPICOM_CERTIFICATE_SAVE_AS_TYPE.CAPICOM_CERTIFICATE_SAVE_AS_CER, CAPICOM_CERTIFICATE_INCLUDE_OPTION.CAPICOM_CERTIFICATE_INCLUDE_WHOLE_CHAIN);

                    String alias = ocert.SubjectName.Replace(" ", "-").Replace(",","").Replace(".","") + ocert.SerialNumber;

                    // And build the new Java truststore
                    if (storeName.Contains("Root"))
                        //Process.Start("c:\\j2sdk1.4.2_10\\bin\\keytool.exe","-import -noprompt -trustcacerts -alias " + ocert.Thumbprint + " " + "-file " + filename + " " + "-keypass password -keystore " + keyStorePath + " " + "-storepass changeit");
                        Interaction.Shell(keytoolPath + " -import -noprompt -trustcacerts -alias " + alias + " " + "-file " + filename + " " + "-keypass password -keystore " + keyStorePath + " " + "-storepass " + keyStorePassword,AppWinStyle.NormalFocus,true,-1);
                    else
                        //Process.Start("c:\\j2sdk1.4.2_10\\bin\\keytool.exe","-import -noprompt -alias " + ocert.Thumbprint + " " + "-file " + filename + " " + "-keypass password -keystore " + keyStorePath + " " + "-storepass changeit");
                        Interaction.Shell(keytoolPath + " -import -noprompt -alias " + alias + " " + "-file " + filename + " " + "-keypass password -keystore " + keyStorePath + " " + "-storepass " + keyStorePassword, AppWinStyle.NormalFocus, true, -1);

                    counter++;   
                }
                Console.Write("\n");
            }            
            Console.ReadLine();
		}
	}
}

